<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import courseItem from "@/components/course_item/course_item.vue";
import loading from "@/components/loading/loading.vue";
import { useMyToastStore } from "@/store/myToast";

const myToast = useMyToastStore();
const instance = getCurrentInstance();
const util = instance?.proxy?.$util;
const request = instance?.proxy?.$request;

let showPage = ref(false);
let popupShow = ref(false);
let headerHeight = ref(0);
let todayDate = ref("");
const startDate = uni.getStorageSync("startDate")
  ? uni.getStorageSync("startDate")
  : uni.$u.timeFormat(Number(new Date()), "yyyy-mm-dd");

let weekList = reactive([
  { name: "一", date: "" },
  { name: "二", date: "" },
  { name: "三", date: "" },
  { name: "四", date: "" },
  { name: "五", date: "" },
  { name: "六", date: "" },
  { name: "日", date: "" },
]);

let swiperIndex = ref(0);
const handleSwiperChange = (e) => {
  swiperIndex.value = e.detail.current;
  getDay(startDate, swiperIndex.value + 1);
};
// 格式化课表
const colorList = [
  "#F2D585",
  "#F09184",
  "#A9D183",
  "#B6BAF5",
  "#92D0AF",
  "#E8B0A0",
  "#E5A2B0",
  "#D3A6C8",
  "#99CCFF",
  "#CCCCFF",
  "#99CCCC",
  "#66CCFF",
  "#6699CC",
  "#FFCC99",
  "#FF6666",
  "#66CCCC",
  "#FFCCCC",
];
let courseList = reactive([]);
const refresherrefresh = () => {
  refresherTriggered.value = true;
  uni.showModal({
    title: "刷新课表？",
    content: "这将会覆盖你原本的课表",
    success: async (res) => {
      if (res.confirm) {
        getUserCourseList();
      } else {
        refresherTriggered.value = false;
      }
    },
  });
};
// 请求课表
let userInfo = uni.getStorageSync("userInfo") || {};
onShow(() => {
  userInfo = uni.getStorageSync("userInfo") || {};
});
const termData = uni.getStorageSync("termData");
const getUserCourseList = async (
  year = termData?.year ? termData?.year : new Date().getFullYear() - 1,
  term = termData?.term ? termData?.term : 2
) => {
  if (!refresherTriggered.value) {
    showPage.value = false;
  }
  try {
    if (term == 1) {
      term = 3;
    } else if (term == 2) {
      term = 12;
    } else {
      term = 16;
    }
    const result = await request.post("courseList", {
      year,
      term,
      cookie: userInfo.cookie,
      account: userInfo.account,
    });
    if (result.status == 200) {
      if (result.data.kbList.length == 0) {
        myToast.params = {
          type: "warning",
          message: "无结果，请尝试更换学期",
        };
        refresherTriggered.value = false;
        showPage.value = true;
        return;
      }
      let i = 0;
      let idList = [];
      courseList = Array.apply(null, { length: 20 }).map(() => []);
      result.data.kbList.forEach((item) => {
        // 格式化周数
        item.zcd = item.zcd.split(",");
        for (let i = 0; i < item.zcd.length; i++) {
          // 判断单双周
          if (item.zcd[i].includes("单")) {
            let numList = item.zcd[i].match(/\d+/g);
            item.zcd.splice(i, 1);
            for (let j = Number(numList[0]); j <= Number(numList[1]); j++) {
              if (j % 2 != 0) {
                item.zcd.push(`${j}`);
              }
            }
          } else if (item.zcd[i].includes("双")) {
            let numList = item.zcd[i].match(/\d+/g);
            item.zcd.splice(i, 1);
            for (let j = Number(numList[0]); j <= Number(numList[1]); j++) {
              if (j % 2 == 0) {
                item.zcd.push(`${j}`);
              }
            }
          }
          // 其他
          item.zcd[i] = item.zcd[i].match(/\d+/g);
          if (item.zcd[i].length == 1) {
            item.zcd[i][1] = item.zcd[i][0];
          }
          for (
            let j = Number(item.zcd[i][0]);
            j <= Number(item.zcd[i][1]);
            j++
          ) {
            courseList[j - 1].push(item);
          }
        }
        // 格式化节数
        item.jcs = item.jcs.split("-");
        // color
        if (idList.includes(item.kcmc)) {
          item.bgColor = colorList[idList.indexOf(item.kcmc)];
        } else {
          idList.push(item.kcmc);
          item.bgColor = colorList[i];
          i++;
        }
      });
      refresherTriggered.value = false;
      uni.setStorageSync("courseList", courseList);
      uni
        .redirectTo({
          url: "/pages/index/courseList",
        })
        .then(() => {
          myToast.params = {
            type: "success",
            message: "课表获取成功",
          };
        });
    } else {
      showPage.value = true;
      myToast.params = {
        type: "error",
        message: "课表获取失败，请尝试重新登录",
        complete() {
          uni.navigateTo({
            url: "/pages/user/login",
          });
        },
      };
      refresherTriggered.value = false;
    }
  } catch (error) {
    console.log(error);
    myToast.params = {
      type: "error",
      message: "课表获取失败，请稍后重试",
    };
    showPage.value = true;
    refresherTriggered.value = false;
  }
};
if (uni.getStorageSync("courseList")) {
  courseList = uni.getStorageSync("courseList");
} else {
  request
    .post("schoolCalendar", {
      cookie: userInfo.cookie,
      account: userInfo.account,
    })
    .then(({ data }) => {
      let date = data.substring(data.indexOf("<tr"), data.indexOf("</tr>"));
      let dateRes = date.substring(
        date.lastIndexOf('">') + 2,
        date.lastIndexOf("</th>")
      );
      // 获取当前学期课表
      let dfYear = dateRes.slice(0, 4);
      let termIndex = dateRes.indexOf("学年") + 2;
      let dfTerm = dateRes.slice(termIndex, termIndex + 1);
      getUserCourseList(dfYear, dfTerm);
      uni.setStorageSync("showTodayCourse", true);
      uni.setStorageSync("termData", {
        year: dfYear,
        term: dfTerm,
      });
      // 获取当前开学日期
      let dfDate = dateRes.slice(
        dateRes.indexOf("(") + 1,
        dateRes.indexOf("至")
      );
      uni.setStorageSync("startDate", dfDate.replaceAll("-", "/"));
    });
}
// 获取周次日期
const getDay = (date, week) => {
  // 开始
  for (let i = 0; i < 7; i++) {
    const data = new Date(date);
    data.setDate(data.getDate() - data.getDay() + 1);
    data.setTime(data.getTime() + 7 * 86400000 * (week - 1) + 86400000 * i);
    let month = (data.getMonth() + 1).toString().padStart(2, "0");
    let day = data.getDate().toString().padStart(2, "0");
    weekList[i].date = `${month}-${day}`;
  }
};
todayDate.value = uni.$u.timeFormat(Number(new Date()), "mm-dd");
let week = util.getWeek(
  uni.$u.timeFormat(Number(new Date()), "yyyy/mm/dd"),
  startDate
);
swiperIndex.value = week - 1;
getDay(startDate, week);
// 获取每节课开始和结束时间
let classPeriod = reactive([]);
const setMorningPeriod = (period, count) => {
  return new Promise((resolve) => {
    let startTime = new Date(`2001/04/27 ${period}`);
    let endtTime = new Date(`2001/04/27 ${period}`);
    endtTime = new Date(endtTime.setMinutes(endtTime.getMinutes() + 40));
    for (let i = 0; i < count; i++) {
      let minutes = 40 + 10;
      if (i == 0) {
        minutes = 0;
      }
      let start = new Date(
        startTime.setMinutes(startTime.getMinutes() + minutes)
      )
        .toTimeString()
        .slice(0, 5);
      let end = new Date(endtTime.setMinutes(endtTime.getMinutes() + minutes))
        .toTimeString()
        .slice(0, 5);
      classPeriod.push({ start, end });
    }
    resolve();
  });
};
onLoad(async () => {
  await setMorningPeriod("08:00", 5);
  await setMorningPeriod("14:30", 4);
  await setMorningPeriod("19:30", 2);
  if (uni.getStorageSync("courseList")) {
    showPage.value = true;
  }
});
//设置相关
let setShow = ref(false);
const handleTermSetting = () => {
  uni.showActionSheet({
    itemList: [
      `${new Date().getFullYear() - 1}-${new Date().getFullYear()} 第一学期`,
      `${new Date().getFullYear() - 1}-${new Date().getFullYear()} 第二学期`,
      `${new Date().getFullYear()}-${new Date().getFullYear() + 1} 第一学期`,
    ],
    success: ({ tapIndex }) => {
      uni.showModal({
        title: "更换学期？",
        content: "这将会覆盖你原本的课表",
        success: async (res) => {
          if (res.confirm) {
            showPage.value = false;
            if (tapIndex == 0) {
              getUserCourseList(new Date().getFullYear() - 1, 1);
              uni.setStorageSync("termData", {
                year: new Date().getFullYear() - 1,
                term: 1,
              });
            } else if (tapIndex == 1) {
              getUserCourseList(new Date().getFullYear() - 1, 2);
              uni.setStorageSync("termData", {
                year: new Date().getFullYear() - 1,
                term: 2,
              });
            } else {
              getUserCourseList(new Date().getFullYear(), 1);
              uni.setStorageSync("termData", {
                year: new Date().getFullYear(),
                term: 1,
              });
            }
          }
        },
      });
    },
  });
};
// 开学时间
let dateTimeShow = ref(false);
const dateTimeValue = Number(new Date());
const handleDatetConfirm = (e) => {
  let data = uni.$u.timeFormat(e.value, "yyyy/mm/dd");
  uni.setStorageSync("startDate", data);
  dateTimeShow.value = false;
  uni.redirectTo({
    url: "/pages/index/courseList",
  });
};
// 首页显示课表
const indexShowCourse = () => {
  uni.showModal({
    title: "首页'今日课表'",
    content: "开启或关闭首页'今日课表'？",
    cancelText: "关闭",
    confirmText: "开启",
    success: function (res) {
      setShow.value = false;
      if (res.confirm) {
        uni.setStorageSync("showTodayCourse", true);
        myToast.params = {
          type: "success",
          message: "首页今日课表已打开",
        };
      } else if (res.cancel) {
        uni.setStorageSync("showTodayCourse", false);
        myToast.params = {
          type: "warning",
          message: "首页今日课表已关闭",
        };
      }
    },
  });
};
// 获取高度
const query = uni.createSelectorQuery().in(instance);
query
  .select(".header-navbar")
  .boundingClientRect((data) => {
    headerHeight.value = data.height;
  })
  .exec();
let refresherTriggered = ref(false);
let weekHeaderHeight = ref(0);
query
  .select(".week-header")
  .boundingClientRect((data) => {
    weekHeaderHeight.value = data.height;
  })
  .exec();

// 点击课程
let showCoursePopup = ref(false);
let adjustCourseBgColor = ref("");
let adjustCourseList = reactive([]);
let showAdjustLoading = ref(false);
let isRequest = ref(false);
let courseName = ref("");
const handleItemClick = (item) => {
  if (isRequest.value) {
    return;
  }
  courseName.value = item.kcmc;
  showAdjustLoading.value = false;
  adjustCourseList.length = 0;
  showCoursePopup.value = true;
  adjustCourseBgColor.value = item.bgColor;
  getAdjustCourseList(item.jxb_id);
};
// 获取调课信息
const getAdjustCourseList = async (id) => {
  isRequest.value = true;
  try {
    const { data } = await request.post("adjustCourseList", {
      cookie: userInfo.cookie,
      account: userInfo.account,
      id,
    });
    isRequest.value = false;
    let modelList = data.slice(data.indexOf("modelList"), -1);
    let adjustList = modelList.slice(
      modelList.indexOf("('") + 2,
      modelList.indexOf("');")
    );
    adjustCourseList.push(...JSON.parse(adjustList));
    console.log(adjustCourseList);
    showAdjustLoading.value = true;
  } catch (error) {
    isRequest.value = false;
    showAdjustLoading.value = true;
    myToast.params = {
      type: "error",
      message: "记录获取失败，请稍后重试",
    };
  }
};
const handleCoursePopupClose = () => {
  showCoursePopup.value = false;
  showAdjustLoading.value = false;
  adjustCourseList.length = 0;
};
</script>

<template>
  <view class="course-list">
    <myToast></myToast>
    <loading v-if="!showPage"></loading>
    <view class="header-navbar">
      <u-navbar autoBack placeholder leftIconSize="38">
        <template #center>
          <text
            class="text-16 text-bold-700"
            @click="!setShow && (popupShow = true)"
            >第{{ swiperIndex + 1 }}周</text
          >
        </template>
      </u-navbar>
      <view class="week-popup-box">
        <u-popup :show="popupShow" @close="popupShow = false">
          <view class="set-period-box">
            <u-grid :border="false" col="4">
              <u-grid-item v-for="item in 20" :key="item">
                <view
                  class="grid-item"
                  @click="handleSwiperChange({ detail: { current: item - 1 } })"
                >
                  <view
                    class="item-text text-center"
                    :class="item - 1 == swiperIndex ? 'select-item' : ''"
                    >第{{ item }}周</view
                  >
                </view>
              </u-grid-item>
            </u-grid>
          </view>
        </u-popup>
      </view>
    </view>
    <!-- 顶部星期日期 -->
    <view class="week-header flex" :style="{ top: `${headerHeight}px` }">
      <view
        class="week-item flex align-center justify-center"
        style="width: 76rpx"
        @click="setShow = !setShow"
      >
        <view
          class="setting-icon-box ml-xs"
          :class="setShow ? 'setting-icon-box' : ''"
        >
          <u-icon class="setting-icon" name="setting" size="42"></u-icon>
        </view>
        <view class="setting-outside">
          <u-transition :show="setShow" mode="fade">
            <view class="setting-box">
              <view class="setting-box-item" @click.stop="indexShowCourse">
                <text>首页"今日课表"</text>
              </view>
              <view class="setting-box-item" @click.stop="handleTermSetting">
                <text>学期设置</text>
              </view>
              <view class="setting-box-item" @click.stop="dateTimeShow = true">
                <text>学期开始时间</text>
              </view>
            </view>
          </u-transition>
        </view>
        <!-- 学期开始时间 -->
        <u-datetime-picker
          :show="dateTimeShow"
          v-model="dateTimeValue"
          mode="date"
          confirmColor="#109363"
          @close="dateTimeShow = false"
          closeOnClickOverlay
          @cancel="dateTimeShow = false"
          @confirm="handleDatetConfirm"
        ></u-datetime-picker>
        <u-transition :show="setShow" mode="fade">
          <view class="mask-box" @click.stop="setShow = false"></view
        ></u-transition>
      </view>
      <view
        class="week-item flex-sub"
        :class="todayDate == item.date ? 'week-today' : ''"
        v-for="(item, index) in weekList"
        :key="index"
      >
        <view class="week-text text-center">周{{ item.name }}</view>
        <view class="week-date text-center">{{ item.date }}</view>
      </view>
    </view>
    <scroll-view
      :refresher-enabled="true"
      :refresher-triggered="refresherTriggered"
      @refresherrefresh="refresherrefresh"
      :style="{ height: `calc(100vh - ${headerHeight + weekHeaderHeight}px)` }"
      :scroll-y="true"
    >
      <swiper
        class="swiper"
        :current="swiperIndex"
        @change="handleSwiperChange"
        :duration="300"
      >
        <swiper-item v-for="(item, index) in courseList" :key="index">
          <view class="list-content">
            <!-- 课程 -->
            <view class="class-period-box flex">
              <!-- 侧边栏 -->
              <view class="class-period">
                <view class="period-box">
                  <view
                    class="count-item flex flex-column justify-center course-item-height"
                    v-for="(item, index) in classPeriod"
                    :key="index"
                  >
                    <view class="text-center">{{ index + 1 }}</view>
                    <view class="time-box">{{ item.start }}</view>
                    <view class="time-box">{{ item.end }}</view>
                  </view>
                </view>
              </view>
              <!-- 课程 -->
              <courseItem
                style="flex: 1"
                :itemList="item"
                @itemClick="handleItemClick"
              ></courseItem>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </scroll-view>
    <view
      class="go-back flex align-center justify-center"
      v-show="swiperIndex != week - 1"
      @click="swiperIndex = week - 1"
    >
      <view style="padding-right: 4rpx" v-show="swiperIndex > week - 1">
        <u-icon
          class="back-icon"
          name="arrow-left"
          color="#969EAC"
          size="36"
        ></u-icon>
      </view>
      <view style="padding-left: 4rpx" v-show="swiperIndex < week - 1">
        <u-icon
          class="back-icon"
          name="arrow-right"
          color="#969EAC"
          size="36"
        ></u-icon>
      </view>
    </view>
    <!-- 课程弹窗 -->
    <view class="coruse-popup-box">
      <u-popup :show="showCoursePopup" @close="showCoursePopup = false">
        <view class="adjust-list">
          <view class="adjust-title flex justify-between align-center">
            <view class="course-name">
              <text class="text-bold-700">{{ courseName }}</text>
              <text class="end-course">调课记录</text>
            </view>
            <view class="ic-close-box" @click="handleCoursePopupClose">
              <u-icon name="close" color="#606165" size="38"></u-icon>
            </view>
          </view>
          <scroll-view class="adjust-content-box" :scroll-y="true">
            <view class="adjust-content">
              <view
                class="adjust-loading-box flex align-center justify-center"
                v-show="!showAdjustLoading"
              >
                <u-loading-icon size="66" mode="circle"></u-loading-icon>
              </view>
              <view
                class="adjust-item"
                v-for="(item, index) in adjustCourseList"
                :key="index"
              >
                <view class="course-item flex flex-column">
                  <view class="before-course">
                    <view class="course-left">
                      <view class="course-name">
                        <text>第{{ item.yzcd }} 星期{{ item.yxqj }}</text>
                        <text class="course-time ml-xs">{{ item.yjsxm }}</text>
                      </view>
                      <view class="course-time"
                        >{{ item.yjc }}
                        <text class="ml-xxs"> @{{ item.ycdmc }}</text></view
                      >
                    </view>
                    <view class="course-right">调动前</view>
                  </view>
                  <view
                    class="last-course"
                    v-if="item.xcd_id"
                    :style="{ backgroundColor: adjustCourseBgColor }"
                  >
                    <view class="course-left">
                      <view class="course-name">
                        <text>第{{ item.xzcd }} 星期{{ item.xxqj }}</text>
                        <text class="course-time ml-xs">{{ item.xjsxm }}</text>
                      </view>
                      <view class="course-time"
                        >{{ item.xjc }}
                        <text class="ml-xxs">@{{ item.xcdmc }}</text>
                      </view></view
                    >
                    <view class="course-right">调动后</view>
                  </view>
                </view>
                <view class="adjust-reason flex align-center">
                  <view class="reason-left">调动原因：</view>
                  <view class="reason-right"> {{ item.tkyy }} </view>
                </view>
              </view>
              <view class="null-box" v-if="adjustCourseList.length == 0">
                <image src="/static/tongzhi.png" mode="widthFix" />
                <text>调课记录为空</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<style scoped lang="scss">
.course-list {
  .week-popup-box {
    :deep(.u-popup__content) {
      border-radius: 24rpx 24rpx 0 0 !important;
    }
    .set-period-box {
      padding: 24rpx;
      .grid-item {
        width: 100%;
        padding: 12rpx;
        box-sizing: border-box;
        .item-text {
          padding: 16rpx;
          font-size: 28rpx;
          background-color: #f5f6f8;
          border-radius: 12rpx;
        }
        .select-item {
          color: #109363;
          background-color: #1093630a;
        }
      }
    }
  }
  .week-header {
    position: sticky;
    left: 0;
    right: 0;
    z-index: 9;
    padding: 14rpx 0 8rpx;
    background-color: #fdfdfd;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    .week-item {
      position: relative;
      .week-date {
        color: #999;
        font-size: 24rpx;
        transform: scale(0.8);
      }
      .setting-icon-box {
        z-index: 999;
        .setting-icon {
          border-radius: 50%;
          box-shadow: 0 4px 44px 0 rgba(0, 0, 0, 0.2),
            0 6px 44px 0 rgba(0, 0, 0, 0.19);
        }
      }
      .setting-outside {
        position: absolute;
        top: 56rpx;
        left: 68rpx;
        z-index: 9999;
      }
      .setting-box {
        padding: 12rpx;
        background-color: #fff;
        color: #333;
        border-radius: 0 20rpx 20rpx 20rpx;
        box-shadow: 0 4px 44px 0 rgba(0, 0, 0, 0.2),
          0 6px 44px 0 rgba(0, 0, 0, 0.19);
        &-item {
          padding: 16rpx 28rpx;
          white-space: nowrap;
          text-align: center;
        }
      }
      .mask-box {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 998;
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(8px);
      }
    }
    .week-today {
      color: #109363 !important;
      background-color: #10936333;
      border-radius: 12rpx;
      .week-date {
        color: #109363 !important;
      }
    }
  }
  .swiper {
    height: 1888rpx;
    .list-content {
      .class-period-box {
        border-bottom: 1px solid #eee;
        border-top: 1px solid #eee;
      }
      .class-period {
        width: 76rpx;
        .period-box {
          padding: 0 4rpx;
          background-color: #fdfdfd;
          border-right: 1px solid #f0f0f0;
          border-left: 1px solid #f0f0f0;
          .count-item {
            border-bottom: 1px solid #f0f0f0;
            &:last-child {
              border-bottom: none;
            }
            .time-box {
              font-size: 24rpx;
              transform: scale(0.8);
              text-align: center;
              color: #999;
            }
          }
          .course-item-height {
            height: 160rpx !important;
          }
        }
      }
    }
  }
  .go-back {
    width: 88rpx;
    height: 88rpx;
    position: fixed;
    bottom: 88rpx;
    right: 58rpx;
    background-color: #e1e1e1aa;
    border-radius: 50%;
    color: #606266;
  }
  :deep(.u-picker__view) {
    height: 488rpx !important;
    .u-picker__view__column__item {
      line-height: 34px !important;
    }
  }
  .coruse-popup-box {
    :deep(.u-popup__content) {
      border-radius: 24rpx 24rpx 0 0 !important;
    }
    .adjust-list {
      .adjust-title {
        padding: 28rpx 20rpx 16rpx;
        margin: 0 20rpx;
        border-bottom: 1px solid #f1f3f5;
        .course-name {
          font-size: 32rpx;
          .end-course {
            margin-left: 24rpx;
            color: #606165;
            font-size: 24rpx;
          }
        }
      }
      .adjust-content-box {
        height: 50vh;
        .adjust-content {
          padding: 28rpx;
          .adjust-loading-box {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 999;
            background-color: #fff;
          }
          .adjust-item {
            padding: 28rpx 32rpx;
            margin-bottom: 32rpx;
            background-color: #fff;
            border-radius: 18rpx;
            box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.14);
            font-size: 28rpx;
            &:last-child {
              margin-bottom: 0;
            }
            .course-item {
              .before-course,
              .last-course {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 12rpx 18rpx;
                border-radius: 12rpx;
                background-color: #f1f3f5;
                color: #9198a3;
                .course-name {
                  font-size: 26rpx;
                  margin-bottom: 4rpx;
                }
                .course-time {
                  font-size: 12px;
                  color: #9198a3;
                }
              }
              .last-course {
                margin-top: 24rpx;
                color: #fff;
                .course-time {
                  color: #ffffffcc !important;
                }
              }
              .course-right {
                font-size: 24rpx;
              }
            }
            .adjust-reason {
              margin-top: 24rpx;
              .reason-left {
                color: #606165;
                white-space: nowrap;
              }
              .reason-right {
                color: #333;
              }
            }
          }
          .null-box {
            padding: 88rpx 188rpx 0;
            text-align: center;
            color: #aaa;
            image {
              height: auto;
            }
          }
        }
      }
    }
  }

  :deep(.my-toast) {
    .u-transition {
      z-index: 10080 !important;
    }
  }
}
</style>
